<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Day9课后作业</title>
</head>

<body>

</body>
<script>
	//补零
	function addZero(num) {
		return num < 10 ? "0" + num : num
	}
	// 1.获取当月有多少天 (getDays)  下个月的0号就是上个月的最后一天
	function getDays(month, year) {
		year = year || 2022
		var date = new Date(year, month, 0)
		return date.getDate()
	}
	// 2.将日期格式化输出"2015-08-24 22:33:44" (forMat)
	function forMat(format, time) {
		// 没传需要格式化的时间默认为当前时间
		var date = time ? new Date(time) : new Date()
		var year = date.getFullYear()
		var month = date.getMonth() + 1
		var day = date.getDate()
		var hour = date.getHours()
		var minute = date.getMinutes()
		var second = date.getSeconds()
		return format.replace("YYYY", year).replace("MM", addZero(month)).replace("DD", addZero(day)).replace("hh", addZero(hour)).replace("mm", addZero(minute)).replace("ss", addZero(second))
	}
	// 3.计算N天后的日期 (getNDate)
	function getNDate(n, time) {
		//如果没传入时间则默认为当前时间的n天后，否则计算传入时间的n天后
		var date = time ? new Date(time) : new Date()
		var day = date.getDate() + n
		var newDate = date.setDate(day)
		return forMat('YYYY-MM-DD hh:mm:ss', newDate)
	}
	// 4.两个时间的差距 (dateGap) 输出'XX天 XX时XX分XX秒'
	function dateGap(time1, time2) {
		var timer = Math.abs((new Date(time1).getTime() - new Date(time2).getTime()) / 1000)
		var day = parseInt(timer / 60 / 60 / 24)
		var hour = parseInt(timer / 60 / 60 % 24)
		var minute = parseInt(timer / 60 % 60)
		var seconds = parseInt(timer % 60)
		return `${day}天${hour}时${minute}分${seconds}秒`
	}

</script>

</html>